var actpro_contentsbill = require('../../model/pro_contents')
var actcart = require('../../sys/cart')

var app = getApp();
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    attrStyle: {
      type: Object,
      default: ''
    },
    customBuybuttonStyle: { //立即购买样式
      type: String,
      default: ''
    },
    customAddbuttonStyle: { //加入购物车样式
      type: String,
      default: ''
    },
    customChoosedStyle: { //已选择样式
      type: String,
      default: ''
    },
    customPopupStyle: { //弹出层样式
      type: String,
      default: ''
    },
    customUnchoosedStyle: { //未选择样式
      type: String,
      default: ''
    },
    imgmode: { //图片模式 big 大图 small小图
      type: String,
      default: 'big'
    },
    btntype: { //按钮类型 square round
      type: String,
      default: 'square'
    },
    color: { //主色
      type: String,
      default: '#333333'
    },
    icon: { //图标名
      type: String,
      default: 'close'
    },
    mainimgshow: { //主图显示
      type: Boolean,
      default: true
    },
    nameshow: { //标题显示
      type: Boolean,
      default: true
    },
    weightshow: { //标题显示
      type: Boolean,
      default: false
    },
    pricecolor: { //价格颜色
      type: String,
      default: '#333333'
    },
    markpricecolor: { //划线价格颜色
      type: String,
      default: '#999999'
    },
    subcolor: { //副颜色
      type: String,
      default: '#333333'
    },
    titlecolor: { //标题颜色
      type: String,
      default: '#333333'
    },
    // btype: { //底部样式
    //   type: Number,
    //   value: 3,
    //   observer: function (newVal, oldVal) {
    //     this.setData({
    //       btype: newVal,
    //     })
    //   }
    // },

  },

  /**
   * 组件的初始数据
   */
  data: {
    unit:'￥',
    attrcss: {
      bottom: {
        css: "",
        btncartcss: "",
        btnbuycss: ""
      }

    },
    popupblock: true,
    objmodel: null,
    shadestatus: false,
    activityid: 0,
    groupid: "",
    taskname: "购买值",
    disablednum: true, //可以变数量 true可以,false 不可以
    maxnum:100000,//单次最大购买
    addbtnname:"加入购物车",
    buybtnname:"立即购买",
  },
  ready: function () {

    if( app.globalData.configdata && app.globalData.configdata.prothem && app.globalData.configdata.prothem.popup){
       var update={}
       if(app.globalData.configdata.prothem.popup.proconfig.addbtnname){
        update['addbtnname']=app.globalData.configdata.prothem.popup.proconfig.addbtnname
       }
       if(app.globalData.configdata.prothem.popup.proconfig.buybtnname){
        update['buybtnname']=app.globalData.configdata.prothem.popup.proconfig.buybtnname
       }
       this.setData(update)
    }

    if (app.globalData.configdata && app.globalData.configdata.task && app.globalData.configdata.task.taskname) {
      this.setData({
        taskname: app.globalData.configdata.task.taskname
      })
    }
    var config=getApp().globalData.configdata
    if(config && config.yihuo && config.yihuo.status==1){
      if(config.payment && config.payment.balancepayunit){
        this.setData({
          unit:config.payment.balancepayunit
        })
      }
      
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // id产品id, activityid活动id,atype活动类型,type底部样式 1加购 2立即购买 3两种 ,selected已选
    setpro(options) {

      var that = this;
      wx.getSystemInfo({
        success: function (res) {
          console.log("systemInfo")

          console.log(res)
          that.setData({
            systemInfo: res
          });
        }
      })

      var that = this;

      if (options.aid) {
        var activityid = options.aid;
      } else {
        var activityid = 0;
      }
      var cid = 0;
      if (options.atype) {
        var activitytype = options.atype;
        cid = activitytype
      } else {
        var activitytype = 0;
      }
      var protype = 1;
      var clubid = -1;
      var clubmode = -1;
      if (options.protype) {
        protype = options.protype;
        if (options.protype == 2) {
          console.log("options.clubid")

          console.log(options.clubid)
          if (options.clubid) {
            clubid = options.clubid
          }

          if (options.clubmode) {
            clubmode = options.clubmode;
          }
        }

      }
      if (options.groupid) {
        var groupid = options.groupid;
      }
      var pronum = 1;
      console.log("xxxxxxxxxxxxxxxxxxxxx")
      console.log(options)

      if (options.fixednum) {
        pronum = options.fixednum;
        this.setData({
          disablednum: false
        })
      }
      // console.log("xxxxxxxxxxxxxxxxxxxxx")
      // console.log(options)
      // var activitytype = options.atype;
      var id = options.proid;
      var selected = options.selected;
      this.setData({
        clubmode: clubmode,
        clubid: clubid,
        protype: protype, //团长产品 2 商城产品1
        groupid: groupid,
        atype: activitytype, //活动类型
        btype: options.type, //事件类型 1加购 2立即购买
        objmodel: null,
        shadestatus: true,
        activityid: activityid, //活动id
        selected: { //已选择
          protype: protype,
          clubid: clubid,
          // activityid: activityid,//活动id
          cid: cid, //0普通产品 1秒杀 2团购
          num: pronum, //数量
          attrs: [], //属性
          stock: 0, //库存
          price: -1, //价格
          realprice: -1, //实际价格
          maxbuy: -100, //最大购买
          activityprice: -1, //活动价
          flag: -1,
          pnum: -2,
          weight: -1,
          buynum: -1
        }
      });

      actpro_contentsbill.showproinfo(id, activityid, activitytype, protype).then(function (paradata) {
        console.log("paradata")

        console.log(paradata)

        if (paradata["status"] == 1) {

          var updatemodel = {
            objmodel: paradata["obj"]
          }

          updatemodel["selected.name"] = paradata["obj"]["name"];
          if (paradata["obj"]['activitybrief'] && paradata["obj"]['activitybrief']['itype'] == 3) {
           
            
            if(paradata["obj"]['activitybrief']['buynumpro'] && paradata["obj"]['activitybrief']['buynumpro'][id] ){
              updatemodel['maxnum']=paradata["obj"]['activitybrief']['buynumpro'][id]['singlebuytimes']
              updatemodel['selected.buynum'] = paradata["obj"]['activitybrief']['buynumpro'][id]['singlebuynum'] * paradata["obj"]['activitybrief']['buynumpro'][id]['peoples']

            }else{
              updatemodel['selected.buynum'] = 100
            }
          }

         
          var getdefaultattr = "-1";

          if (paradata["obj"]["guigetype"] == "-1") {
            updatemodel["selected.stock"] = paradata["obj"]["stock"];
            updatemodel["selected.weight"] = paradata["obj"]["weight"];
            updatemodel["selected.realprice"] = paradata["obj"]["realprice"];
            updatemodel["selected.price"] = paradata["obj"]["price"];
          } else {
            updatemodel["selected.stock"] = -1;
            updatemodel["selected.weight"] = -1;
            var attrs = [];

            for (var a in paradata["obj"]["skuht"]) {
              if (paradata["obj"]["skuht"][a]['isdefault'] == 1 && paradata["obj"]["skuht"][a]['isshow'] == 1) {
                getdefaultattr = a
              }
            }
            if (getdefaultattr == -1) {
              for (var a in paradata["obj"]["skudata"]["grouplabel"]) {
                attrs.push({
                  "keyval": -1,
                  "keyname": ""
                })
              }
            } else {
              var arr = getdefaultattr.split("_")
              for (var i = 0; i < arr.length; i++) {

                attrs.push({
                  "keyval": arr[i],
                  "keyname": paradata["obj"]["skudata"]["grouplabel"][i]["attrs"][arr[i]]
                })

              }
            }

            updatemodel["selected.attrs"] = attrs;
          }
          if (activityid != 0) {
            updatemodel["selected.activityprice"] = paradata["obj"]["activityprice"];
          }
          updatemodel["selected.maxbuy"] = paradata["obj"]["maxbuy"];
          that.setData(updatemodel)
          if (getdefaultattr != -1) {

            that.afterchoosechange()
          }
        }
      }).then(function () {
        if (selected) {
          that.setData({
            selected: selected
          })
        }
      })
    },
    enlarge(e) {
      var dataset = e.currentTarget.dataset;
      var imgsdatas = [];
      for (var i in dataset.imgs) {
        imgsdatas.push(dataset.imgs[i]['simg'])
      }
      wx.previewImage({
        current: dataset.imgs[dataset.index]['simg'], // 当前显示图片的http链接  
        urls: imgsdatas // 需要预览的图片http链接列表  
      })
    },
    //浏览图片
    previewImage: function (e) {
      var that = this;
      var current = e.target.dataset.src;
      var imgsdata = [];
      imgsdata.push(current);
      wx.previewImage({
        current: current, // 当前显示图片的http链接  
        urls: imgsdata // 需要预览的图片http链接列表  
      })
    },
    //弹出框
    popup: function (e) {
      this.setData({
        popupblock: false
      })
    },
    //关闭弹窗
    closepop: function () {
      var that = this;
      that.setData({
        popupblock: true
      })
    },
    // 更新数量
    updatenum(event) {
      var oldnum = this.data.selected.num
      var val = parseInt(event.detail);
      var selected = this.data.selected;
      selected.num = parseInt(val);


      if (selected.num < 1) {
        selected.num = 1;
      }
      //-100 不限库存 -1考虑没选择的情况
      if (selected.maxbuy != -100 && selected.maxbuy > 0) {
        var min = (parseInt(selected.stock) < parseInt(selected.maxbuy)) ? selected.stock : selected.maxbuy

      } else {
        var min = selected.stock
      }

      var limitinfo = this.data.objmodel.limitinfo

      if (limitinfo && limitinfo.limitnum > -1 && selected.num > parseInt(limitinfo.limitnum)) {
        wx.showToast({
          title: '限购' + limitinfo.limitnum + "件",
        })
        selected.num = limitinfo.limitnum;
        // return ;
      }

      if (selected.num >= min && selected.stock != -100 && selected.stock != -1) {
        selected.num = min;
        wx.showToast({
          title: '最多购买' + selected.num + "件",
        })
      }
      var tvl = selected.num
      if (tvl == oldnum) {
        this.setData({
          "selected.num": -1
        })
      }
      this.setData({
        "selected.num": tvl
      })
    },
    // 选择属性颜色
    chooseattr(e) {

      var dataset = e.currentTarget.dataset;
      var one_index = dataset.one_index; //第组
      var two_index = dataset.two_index; //组内每几个元素
      var two_name = dataset.two_name;
      var selected = this.data.selected;
      // var skudata = this.data.objmodel["skudata"];
      // console.log("skuhtskuhtskuhtskuhtskuht")
      // console.log(this.data.objmodel)

      if (selected["attrs"][one_index]["keyval"] == two_index) {
        selected["attrs"][one_index]["keyval"] = -1;
        selected["attrs"][one_index]["keyname"] = "";
      } else {
        selected["attrs"][one_index]["keyval"] = two_index;
        selected["attrs"][one_index]["keyname"] = two_name;
      }

      this.setData(selected)
      this.afterchoosechange()
    },
    afterchoosechange() {
      var updatemodel = {};

      var selected = this.data.selected;

      var skuht = this.data.objmodel["skuht"];

      var pnum = 0;
      var flag = -1; //用来标记最后一个未选的
      var arrkeys = [];
      var updatemodel = {};
      var temval = [];
      //pnum 判断有几个款未选中，如果只剩下一个属性未选择判断缺货
      for (var a in selected["attrs"]) {
        //取选中的值
        temval.push(selected["attrs"][a]["keyval"]);

        if (selected["attrs"][a]["keyval"] == -1) {
          pnum--;
          if (pnum == -2) {
            break;
          }
          flag = a;
        }
      }
      if (pnum == 0 || pnum == -1) {
        var len = temval.length;
        temval.forEach(function (val, i) {

          var newmodel = {
            "startkey": temval.slice(0, i),
            "endkey": []
          };
          if (i < len - 1) {
            newmodel["endkey"] = temval.slice((i + 1), len)
          }
          arrkeys.push(newmodel)
        })
        for (var i = 0, ilen = arrkeys.length; i < ilen; i++) {
          if (arrkeys[i]["startkey"].length > 0) {
            arrkeys[i]["startkey"] = arrkeys[i]["startkey"].join("_") + "_";
          } else {
            arrkeys[i]["startkey"] = "";
          }

          if (arrkeys[i]["endkey"].length > 0) {
            arrkeys[i]["endkey"] = "_" + arrkeys[i]["endkey"].join("_");
          } else {
            arrkeys[i]["endkey"] = "";
          }
        }
      }

      if (pnum == 0) {
        var actattr = skuht[temval.join("_")]


        selected["fullsimg"] = actattr["fullsimg"];

        selected["price"] = actattr["price"];
        selected["realprice"] = actattr["realprice"];
        console.log(skuht)
        console.log(actattr)
        selected["stock"] = actattr["stock"];


        selected["weight"] = actattr["weight"];
        selected["activityprice"] = actattr["activityprice"];
        //不限量
        if (actattr["stock"] != -100 && parseInt(selected["num"]) > actattr["stock"]) {
          selected["num"] = actattr["stock"];
        }
        // var limitinfo =that.data.objmodel.limitinfo
        // if(limitinfo&&limitinfo.limitnum>-1 &&selected.num >parseInt(limitinfo.limitnum)){
        // wx.showToast({
        //   title: '限购' + limitinfo.limitnum + "件",
        // })
        // selected["num"]=limitinfo.limitnum
        // return ;
        // }
      } else {
        //未设价格
        selected["price"] = -1
        selected["realprice"] = -1
      }
      selected["flag"] = flag;
      selected["pnum"] = pnum;
      updatemodel["arrkeys"] = arrkeys;
      updatemodel["selected"] = selected;

      selected['proid'] = this.data.objmodel.id

      console.log("updatemodel")
      console.log(updatemodel)

      this.setData(updatemodel)

      var myEventDetail = selected // detail对象，提供给事件监听函数
      var myEventOption = {} // 触发事件的选项


      this.triggerEvent('attrchoose', myEventDetail, myEventOption)
    },


    chageshadestatus: function (e) {
      var dataset = e.currentTarget.dataset;
      if (dataset["cid"]) {
        this.data.selected.cid = dataset.cid;
      }


      if (dataset.value == "1") {
        this.setData({
          shadestatus: true
        });
      } else {
        this.setData({
          shadestatus: false
        });
      }

    },

    confirmselected(e) {
      var dataset = e.currentTarget.dataset;
      var that = this;
      var selected = this.data.selected;
      var buytype = dataset.buytype; //1加购 2立即买
      var objmodel = that.data.objmodel;

      if (objmodel.guigetype == "1") {
        for (var akey in selected["attrs"]) {
          if (selected["attrs"][akey]["keyval"] == "-1") {
            wx.showToast({
              icon: 'error',
              title: '请选择属性',
            })
            return;
          }
        }
      }

      if (selected.num < 1 || selected.stock < 1) {
        wx.showToast({
          title: '产品已售罄 ',
        })
        return;
      } else {
        //可以进行购买操作

        var newmodel = JSON.parse(JSON.stringify(selected));


        newmodel["id"] = objmodel.id;
        newmodel["name"] = objmodel.name;
        newmodel["bpid"] = objmodel.bpid;


        delete newmodel["stock"];
        if (buytype == 1) {
          if (parseInt(this.data.activityid) != 0) {

            actcart.cartadd(newmodel, newmodel.cid, this.data.activityid);
          } else {

            actcart.cartadd(newmodel);
          }
          var myEventDetail = {} // detail对象，提供给事件监听函数
          var myEventOption = {} // 触发事件的选项
          this.triggerEvent("aftercart", myEventDetail, myEventOption)
          wx.showToast({
            title: '加入购买车成功',
            icon: 'success',
            duration: 2000
          })
          this.setData({
            shadestatus: false
          });
        } else {

          newmodel.attrnameinfo = [];
          if (that.data.activityid) {
            newmodel.activityid = that.data.activityid;
          } else {
            newmodel.activityid = 0
          }
          newmodel.proid = that.data.objmodel.id;

          newmodel.simg = that.data.objmodel.simg;
          newmodel.customdata = that.data.objmodel.customdata;

          
          var xcid = 0;

          if (newmodel.activityid != 0) {
            xcid = newmodel.cid;
          }
          newmodel.keyval = newmodel.proid + "_" + xcid.toString() + "_" + parseInt(newmodel.activityid).toString() + "_";

          if (objmodel.guigetype == "-1") {
            newmodel.keyval = newmodel.keyval + objmodel.guigetype;
            newmodel.weight = objmodel.weight
            newmodel.pro_ident = -1
          } else {
            var keyvalselected = [];
            for (var a in newmodel.attrs) {
              newmodel.attrnameinfo.push({
                attrtitle: objmodel.skudata.grouplabel[a]['grouptitle'],
                attrname: newmodel.attrs[a]["keyname"]
              })
              keyvalselected.push(newmodel.attrs[a]["keyval"]);
            }

            var strkeyvalselected = keyvalselected.join("_")
            var pro_ident = 0;
            for (a in objmodel["skuht"]) {
              if (a == strkeyvalselected) {
                break;
              }
              pro_ident++;
            }
            newmodel.pro_ident = pro_ident;
            newmodel.keyval = newmodel.keyval + keyvalselected.join("x")
          }

          //临时数据(订单支付数据)


          if (this.data.groupid) {
            newmodel['groupid'] = this.data.groupid
          }
          newmodel.keyval = newmodel.keyval + "_" + newmodel.protype
          console.log("newmodel")
          console.log(newmodel)
          app.globalData.temcart = {};
          app.globalData.temcart["data"] = [newmodel];
          var clubmust = this.data.protype == 2 ? '1' : '-1'
          wx.navigateTo({
            url: '/' + app.globalData.xcsys.m + '/shop/paycore/payinfo?iscart=-1&clubid=' + this.data.clubid + '&mode=' + this.data.clubmode + '&clubmust=' + clubmust
          })
        }
      }
    },

  }
})